package com.itheima.health.service.impl;

import com.itheima.health.dao.MemberDao;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 会员SERVICE实现类
 */
@Service
@Slf4j
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    /**
     * 根据id查询会员信息
     *
     * @param memberId
     * @return
     */
    @Override
    public Member findById(Integer memberId) {
        return memberDao.selectById(memberId);
    }


    //根据手机号查询会员信息
    @Override
    public Member selectByTelephone(String telephone) {
        return memberDao.selectByTelephone(telephone);
    }

    //保存会员信息
    @Override
    public void save(Member member) {
        memberDao.insert(member);
    }

    /**
     * 通过手机号查询会员信息，判断是注册(新用户)还是更新(老用户)
     *
     * @param member
     * @return
     */
    @Override
    public Member createOrUpdate(Member member) {
        //通过手机号查询会员
        Member m = memberDao.selectByPhone(member.getPhoneNumber());
        //判断查询到的会员对象是否存在
        if (m != null) {
            //说明这是个老会员，把会员id给member对象
            member.setId(m.getId());
            memberDao.updateMember(member);
        } else {
            //否则是新会员要注册
            //这里缺少一个注册时间regTime
            member.setRegTime(new Date());
            memberDao.insert(member);
        }
        //这里因为不能确定时新增还是老用户，所以根据id再次查询
        return memberDao.selectById(member.getId());
    }
    /**
     * 根据月份集合获取会员数量集合
     * @param months
     * @return
     */
    @Override
    public List<Integer> countByMonth(List<String> months, Map<String,Integer> lastDays) {
      List<Integer> list=new ArrayList<>();
        //遍历月份集合
        for (String month : months) {
            //获得每一个月份
            //取出月份对应的最后一天
            String lastDay = lastDays.get(month).toString();
            //拼接
            String date = month +"."+lastDay;
            //查询数量
            Long count = memberDao.countByRegTimeBefore(date);
            list.add(count.intValue());
        }
        return list;
    }
}

